package com.maimao.kill.job;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.maimao.core.utils.DateUtils;
import com.maimao.kill.mapper.KillGoodsMapper;
import com.maimao.kill.service.KillCacheService;
import com.maimao.kill.service.KillGoodsService;
import com.maimao.kill.service.ScheduleService;
import com.maimao.model.kill.KillGoods;
import com.maimao.model.kill.Schedule;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 每日23点55分 刷新第二天所有排期和对应的秒杀商品到缓存
 *
 * @author MaoLin Wang
 * @date 2021/4/22 下午9:12
 */
@Component
@Slf4j
public class RefreshKillGoodsNextDayJobHandler {
    public static final String TODAY = "today";
    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private KillCacheService killCacheService;

    @Autowired
    private KillGoodsService goodsService;

    @Autowired
    private KillGoodsMapper killGoodsMapper;

    @XxlJob("refreshKillGoodsNextDayJobHandler")
    public ReturnT refreshKillGoodsNextDayJobHandler() {

        //默认刷新第二天数据
        LocalDateTime tomorrow = DateUtils.nextDayBegin();

        //支持刷新今日数据
        boolean todayData = false;
        String today = XxlJobHelper.getJobParam();
        if (!StrUtil.isEmpty(today) && TODAY.equals(today)) {
            tomorrow = tomorrow.minusDays(1);
            todayData = true;
        }
        List<Schedule> scheduleList = scheduleService.queryByStarTimeBetween(tomorrow, tomorrow.plusDays(1));
        if (ObjectUtil.isNotEmpty(scheduleList)) {
            XxlJobHelper.log("查询到" + (todayData ? "今" : "第二") + "日符合条件的排期数：{}", scheduleList.size());
            killCacheService.add(scheduleList);
            for (Schedule schedule : scheduleList) {
                List<KillGoods> killGoodsList = killGoodsMapper.selectByScheduleId(schedule.getId());
                killCacheService.putGoods(schedule.getId(), killGoodsList);
                XxlJobHelper.log("排期{}下商品数{}", schedule, killGoodsList.size());
            }
        }

        return ReturnT.SUCCESS;
    }
}
